package com.hnhs.advice;

import cn.hutool.json.JSONUtil;
import com.hnhs.dto.ResponseDto;
import com.hnhs.exceptions.MyException;
import com.hnhs.info.PageInfo;
import com.hnhs.threadLocal.LocalPageInfoUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;
import java.util.Map;

// 对控制层的增强 主要目的是返回结果
@RestControllerAdvice
public class MyResponseAdvice implements ResponseBodyAdvice<Object> {
    // 开启支持的方法
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // 默认是不增强的
        return true;
    }
    //错误信息匹配
    @ExceptionHandler
    public Object processException(Exception ex){
        if(ex instanceof MyException){
            MyException myException = (MyException)ex;
            return ResponseDto.error(myException.getCode(), ex.getMessage());
        }
        ResponseDto dto=ResponseDto.error(408, ex.getMessage());

        return dto;
    }



    // 支持方法的数据统计信息
    @Override
    public Object beforeBodyWrite(
            Object body,
            MethodParameter methodParameter,
            MediaType mediaType,
            Class<? extends HttpMessageConverter<?>> aClass,
            ServerHttpRequest serverHttpRequest,
            ServerHttpResponse serverHttpResponse) {
        //解决异常后双返回值问题
        if (body instanceof ResponseDto){
            return body;
        }
        //接受数据
        ResponseDto dto = ResponseDto.success(body);
        PageInfo pageInfo= LocalPageInfoUtil.get();
        if (pageInfo !=null){
            Map<Object,Object> map=new HashMap<>();
            map.put("total",pageInfo.getTotal());
            map.put("items",body);
            // 把共享的数据 传递出去
            dto=ResponseDto.success(map);
            //用完之后 remove掉
            LocalPageInfoUtil.remove();
        }
        //把字符串的数据转换为 json数据
        if(aClass == StringHttpMessageConverter.class){
            //改成json字符串
            return JSONUtil.toJsonStr(dto);
        }

        return dto;
    }
}
